﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.astd.common.manager;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class HuanlangLogin : LoginImplBase
    {
        public HuanlangLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            HttpResult resp;
            logging();
            string loginurl = String.Format("http://wwwv3.huanlang.com/Handlers/LoginHandlerGetJOSN.ashx?jsoncallback=jsonp{0}&uname={1}&Pwd={2}&gameid=19",
                TimeMgr.TimeStamp, _username, _password);
            resp = TransferMgr.doGetPure(loginurl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string content = resp.getContent();
            //fail: jsonp1390489353163({data:0})
            //success:jsonp1390489353164({data:1})
            content = content.Substring(content.IndexOf(':') + 1);
            content = content.Substring(0, content.IndexOf('}'));

            if (content.Equals("0"))
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            // get url list
            findingServerUrl();
            string gamelisturl = "http://astd.huanlang.com/server_list.aspx";
            resp = TransferMgr.doGetPure(gamelisturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetServerList; return result; }

            string retstr = resp.getContent();

            // 查找serverid字符串
            string id = _acc.ServerId >= 10 ? _acc.ServerId.ToString() : String.Format("0{0}", _acc.ServerId);
            string district_name = String.Format("双线{0}服", id);
            Regex re = new Regex(String.Format("<a.*href=\"([^\"']*?)\".*>{0}.*</a>", district_name));
            MatchCollection matches = re.Matches(retstr);
            if (matches == null || matches.Count == 0 || matches[0] == null) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }
            if (matches[0].Groups == null || matches[0].Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string redirecturl = matches[0].Groups[1].Value;

            processRedirect(redirecturl, result, ref cookies);

            return result;
        }
    }
}
